package com.ncloud.resman.busi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.JsonUtil;
import com.ncloud.common.utils.DateUtils;
import com.ncloud.common.utils.PageHelperUtils;
import com.ncloud.common.utils.excel.ExcelUtil;
import com.ncloud.resman.constant.ResConstant;
import com.ncloud.resman.entity.*;
import com.ncloud.resman.service.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.ParseException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;


/**
 * Created by shiqiang on 2017/8/15.
 */
@Service
public class DeviceCpeBusi {
    @Autowired
    private DeviceBaseService deviceBaseService;
    @Autowired
    private DeviceCpeService deviceCpeService;
    @Autowired
    private ModelService modelService;
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Object getCpeList(JSONObject json) {
        Object object = null;

        if(PageHelperUtils.isPage(json)){
            PageHelperUtils.setPageParam(json);
            List<JSONObject> list = deviceCpeService.getDeviceCpeList(json.getString("state"));
            if(json.containsKey("deviceId") && !StringUtils.isEmpty(json.getLong("deviceId"))){
                list = list.stream().filter(obj-> Long.parseLong(obj.getString("deviceId")) == json.getLong("deviceId")).collect(Collectors.toList());
            }
            PageInfo pageInfo = new PageInfo(JSON.parseArray(JsonUtil.toJson(list)));
            object = JSON.parseObject(JSON.toJSONString(pageInfo));
        }else{
            List<JSONObject> list =deviceCpeService.getDeviceCpeList(json.getString("state"));
            if(json.containsKey("deviceId") && !StringUtils.isEmpty(json.getLong("deviceId"))){
                list = list.stream().filter(obj-> Long.parseLong(obj.getString("deviceId")) == json.getLong("deviceId")).collect(Collectors.toList());
            }
            object = JSON.parseArray(JsonUtil.toJson(list));
        }
        return object;
    }

    public JSONObject getCpeInfo(Long deviceId){
        JSONObject json = new JSONObject();
        DeviceBase deviceBase = deviceBaseService.getDeviceBaseByDeviceId(deviceId);
        DeviceCpe deviceCpe = deviceCpeService.getDeviceCpeByDeviceId(deviceId);
        json.put("device_base",deviceBase);
        json.put("device_cpe",deviceCpe);
        return json;
    }
    @Transactional
    public void updateCpe(JSONObject json){
        Long userId = null;
        if(json.containsKey("userID")){
            userId = json.getLong("userID");
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"userID 信息不存在");
        }
        if(json.containsKey("device_base")){
            JSONObject base = json.getJSONObject("device_base");
            DeviceBase deviceBase = JSON.parseObject(base.toJSONString(),DeviceBase.class);
            deviceBase.setUpdateUser(userId);
            deviceBaseService.updateDeviceBase(deviceBase);
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_base 节点信息不存在！");
        }

        if(json.containsKey("device_cpe")){
            JSONObject base = json.getJSONObject("device_cpe");
            DeviceCpe deviceCpe = JSON.parseObject(base.toJSONString(),DeviceCpe.class);
            deviceCpe.setUpdateUser(userId);
            deviceCpeService.updateDeviceCpe(deviceCpe);
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_cpe 节点信息不存在！");
        }
    }
    @Transactional
    public void deleteCpeInfo(Long deviceId){
        deviceBaseService.deleteDeviceBase(deviceId);
        deviceCpeService.deleteDeviceCpe(deviceId);
    }

    @Transactional
    public void saveCpe(JSONObject json){
        Long userId = null;
        if(json.containsKey("userID")){
            userId = json.getLong("userID");
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"userID 信息不存在");
        }
        if(json.containsKey("device_base")){
            JSONObject base = json.getJSONObject("device_base");
            DeviceBase deviceBase = JSON.parseObject(base.toJSONString(),DeviceBase.class);
            deviceBase.setCreateUser(userId);
            if(StringUtils.isEmpty(deviceBase.getState())){
                deviceBase.setState(ResConstant.DEVICE_STATE_FREE);
            }
            deviceBaseService.insertDeviceBase(deviceBase);

            if(json.containsKey("device_cpe")){
                JSONObject cpe = json.getJSONObject("device_cpe");
                DeviceCpe deviceCpe = JSON.parseObject(cpe.toJSONString(),DeviceCpe.class);
                deviceCpe.setDeviceId(deviceBase.getDeviceId());
                deviceCpe.setCreateUser(userId);
                deviceCpeService.insertDeviceCpe(deviceCpe);
            }else{
                throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_cpe 节点信息不存在！");
            }
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_base 节点信息不存在！");
        }
    } 
    //导出Excel
    public void exportCPEInfo(String snNum,HttpServletResponse response,boolean template) throws IOException{
    	if(snNum==null||snNum=="")
    	{
    		snNum = null;
    	}
    	List<ExportDeviceCPE> CPEList=new ArrayList<ExportDeviceCPE>();
    	if(template){
    		CPEList=deviceCpeService.exportCPEInfo(snNum);
    	}    	
    	
    	Date date=new Date();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMssHHddmm");
    	OutputStream os = null;
		String fileName = "CPE设备列表_"+sdf.format(date)+".xls";
		response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
        os = response.getOutputStream();
		Map<String, String> map = new HashMap<String, String>();
      // map.put("title", "CPE设备列表");
        map.put("total", CPEList.size()+" 条");
        map.put("date", DateUtils.getDate());
		ExcelUtil.getInstance().exportObj2ExcelByTemplate(map, "cpe-info-template.xls",os, CPEList, ExportDeviceCPE.class, true);
		
		
    }
    //导入Excel
    public String importCPEInfo(InputStream inputStream) throws Exception{
    	List<Object> listInfo=ExcelUtil.getInstance().readExcel2ObjsByInputStream(inputStream, ExportDeviceCPE.class);
    	if(listInfo==null||listInfo.size()==0){
			return "无数据插入";
		}
    	Date date=new Date();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
    	for(int i=0;i<listInfo.size();i++){
    		DeviceBase deviceBase=new DeviceBase();
    		DeviceCpe deviceCpe = new DeviceCpe();
     		ExportDeviceCPE cpeInfo=(ExportDeviceCPE)listInfo.get(i);
     		
     		String snNum=cpeInfo.getSnNum();
     		if(snNum!=null&&snNum!=""){
     		Model model=modelService.getModelInfoById(cpeInfo.getModelId());
    		deviceBase.setSnNum(snNum);
    		deviceBase.setModelId(cpeInfo.getModelId());
    		deviceBase.setBrandName(model.getBrandName());
    		deviceBase.setBrandId(model.getBrandId());
    		deviceBase.setModelName(model.getModelName());
    		deviceBase.setEqptType(model.getEqptType());
    		deviceBase.setEqptSpec(model.getEqptSpec());
    		deviceBase.setState(cpeInfo.getState());
    		Long deviceId=deviceBaseService.insertDeviceBase(deviceBase);
    		
    		deviceCpe.setDeviceId(deviceId);
    		deviceCpe.setCpuModel(cpeInfo.getCpuModel().toString());
    		deviceCpe.setCpuNum(Integer.parseInt(cpeInfo.getCpuNum().toString()));
    		deviceCpe.setMemoryModel(cpeInfo.getMemoryModel().toString());
    		deviceCpe.setMemoryCapacity(cpeInfo.getMemoryCapacity().toString());
    		deviceCpe.setDiskCapacity(cpeInfo.getDiskCapacity().toString());
    		deviceCpe.setDiskModel(cpeInfo.getDiskModel().toString());
    		deviceCpe.setSubNum(Integer.parseInt(cpeInfo.getSubNum().toString()));
    		deviceCpe.setPutDate(sdf.parse(cpeInfo.getPutDate()));
    		deviceCpe.setOutDate(sdf.parse(cpeInfo.getOutDate()));   		
    		deviceCpe.setUseName(cpeInfo.getUseName().toString());
    		deviceCpe.setContactPhone(cpeInfo.getContactPhone().toString());
    		
    		int n = deviceCpeService.insertDeviceCpe(deviceCpe);
     		}else{
     			
     		}
    	}
    	return "插入成功";
    }
}
